<template>
  <div class="bdwx flexcenter">
    <Wxlogin
      :id="id"
      :style="style"
      :href="href"
      :state="state"
      :appid="appid"
      :scope="scope"
      :redirect_uri="redirect_uri"
      :self_redirect="self_redirect"
    />
  </div>
</template>

<script>

import Wxlogin from 'vue-wxlogin'
import { changewx } from '@/api/baseInfo/authority/user'
import { wXGetOpenId } from '@/api/user'
import storage from '@/utils/storage'
import { showNotice } from '@/utils/toolclass'

export default {
  components: { Wxlogin },
  data() {
    return {
      id: 'login_container',
      appid: 'wx4263a501bf57836b',
      scope: 'snsapi_login',
      redirect_uri: encodeURIComponent('http://show.linkpow.cn/#/bindWx'),
      state: Math.ceil(Math.random() * 1000).toString(),
      style: 'black',
      self_redirect: false,
      href: 'data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDIwMHB4O30KLmltcG93ZXJCb3ggLnRpdGxlIHtkaXNwbGF5OiBub25lO30KLmltcG93ZXJCb3ggLmluZm8ge3dpZHRoOiAyMDBweDt9Ci5zdGF0dXNfaWNvbiB7ZGlzcGxheTogbm9uZX0KLmltcG93ZXJCb3ggLnN0YXR1cyB7dGV4dC1hbGlnbjogY2VudGVyO30KLm9sZC10ZW1wbGF0ZXttYXJnaW4tcmlnaHQ6IDEwMHB4O30KaHRtbCB7aGVpZ2h0OjMyMHB4O30KYm9keXt3aWR0aDphdXRvO2hlaWdodDogMzIwcHg7fQouc3RhdHVzX3R4dCB7d2lkdGg6MjAwcHg7bWFyZ2luLWxlZnQ6LTIwcHg7fQ=='
    }
  },
  created() {
    this.$storage.set('upUrl', JSON.stringify({ 'path': '/bindWx' }))
  },
  mounted() {
    this.getWxcode()
  },
  methods: {
    getWxcode() {
      var timer = setInterval(() => {
        var wxurl = window.location.href
        // console.log('mounted', wxurl)
        if (wxurl.indexOf('code') !== -1) {
          clearInterval(timer)
          // this.$router.replace({ path: '/bindWx' })
          // console.log('用户已扫码，进行授权登陆确认111', wxurl)
          const num1 = wxurl.indexOf('code=')
          const num2 = wxurl.indexOf('&state=')
          this.wxcode = wxurl.slice(num1 + 5, num2)
          // console.log('CODE111===', this.wxcode)
          wXGetOpenId(this.wxcode).then(res => {
            if (res.code === '000000') {
              // this.$router.replace({ path: '/bindWx' })
              storage.set('wxId', res.data)
              // console.log('wxInfo111===', res.data)
              changewx(res.data.openid).then(res => {
                if (res.code === '000000') {
                  // console.log(res)
                  showNotice('success', '提示', '绑定成功')
                } else {
                  if (res.msg === '失败') {
                    showNotice('error', '提示', '绑定失败')
                  } else if (res.code === '100052') {
                    showNotice('warning', '提示', '已绑定微信，请勿重复绑定')
                  } else {
                    showNotice('error', '提示', res.msg)
                  }
                }
              })
            }
          })
        }
      }, 1000)
    }
  }
}
</script>

<style lang="scss">
.bdwx {
  margin-top: 10%;
}
</style>
